package com.excemly.library.controller;

import com.excemly.library.entity.Book;
import com.excemly.library.service.BookService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.excemly.library.common.ApiResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Optional; // 导入 Optional 类，解决引用缺失问题
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.excemly.library.exceptions.ResourceNotFoundException; // 导入资源未找到异常类

//处理图书管理接口，包含 /api/books 的GET（搜索图书）和POST（添加图书）
//GET 方法接受查询参数 title、author、isbn 用于搜索图书，调用 BookService 搜索图书并返回结果。
//POST 方法接受 Book 对象用于添加图书，调用 BookService 保存图书并返回成功响应。
@RestController
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping("/api/books")
public class BookController {

    private final BookService bookService;
    private final ObjectMapper objectMapper;

    public BookController(BookService bookService, ObjectMapper objectMapper) {
        this.bookService = bookService;
        this.objectMapper = objectMapper;
    }
   
    @GetMapping
    public ApiResponse searchBooks(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String author,
            @RequestParam(required = false) String isbn,
            Pageable pageable) {
        Page<Book> books = bookService.searchBooks(title, author, isbn, pageable);
        
        // 修正响应格式，添加分页元数据
        Map<String, Object> response = new HashMap<>();
        response.put("data", books.getContent());
        response.put("total", books.getTotalElements());
        return ApiResponse.success("查询成功", response);
    }
    @CrossOrigin 
    @PostMapping
    public ApiResponse createBook(@Validated @RequestBody Book book) {
        Book savedBook = bookService.saveBook(book);
        Map<String, Object> data = new HashMap<>();
        data.put("data", savedBook);
        return ApiResponse.success("书籍创建成功", data);
    }

    @GetMapping("/getbook")
    public ApiResponse getBookById(@PathVariable Long id) {
        Book book = bookService.getBookById(id);
        Map<String, Object> data = new HashMap<>();
        data.put("data", book);
        return ApiResponse.success("获取图书成功", data);
    }

    @PutMapping("/updatedBook")
    public ApiResponse updateBook(@PathVariable Long id, @Validated @RequestBody Book bookDetails) {
        Book updatedBook = bookService.updateBook(id, bookDetails);
        Map<String, Object> data = new HashMap<>();
        data.put("data", updatedBook);
        return ApiResponse.success("书籍更新成功", data);
    }

    @DeleteMapping("/deleteBook")
    public ApiResponse deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        Map<String, Object> data = new HashMap<>();
        data.put("data", null);
        return ApiResponse.success("书籍删除成功", data);
    }

    @GetMapping("/hot")
    public ApiResponse getHotBooks(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        System.out.println("收到热门图书请求 - 客户端IP: " + request.getRemoteAddr() + ", URL: " + request.getRequestURL());
        System.out.println("收到热门图书请求 - 页码: " + page + ", 每页数量: " + pageSize);
        List<Book> hotBooks = bookService.getHotBooks(page, pageSize);
        System.out.println("查询到热门图书数量: " + hotBooks.size() + ", 图书数据: " + hotBooks);
        System.out.println("图书数据详情: " + hotBooks.stream().map(b -> b.getTitle() + " (" + b.getPublishDate() + ")").collect(java.util.stream.Collectors.toList()));
        List<Map<String, Object>> bookList;
        try {
            // 使用全局配置的ObjectMapper进行序列化
            bookList = objectMapper.convertValue(hotBooks, new TypeReference<List<Map<String, Object>>>() {});
        } catch (IllegalArgumentException e) {
            System.err.println("图书数据序列化失败: " + e.getMessage());
            return ApiResponse.error(500, "数据处理失败");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("data", bookList);
        data.put("total", hotBooks.size());
        System.out.println("热门图书接口返回数据: " + data);
        return ApiResponse.success("获取热门图书成功", data);
    }

    @PostMapping("/borrow")
    public ApiResponse borrowBook(@RequestParam Long bookId, @RequestParam Long userId) {
        bookService.borrowBook(bookId, userId);
        Map<String, Object> data = new HashMap<>();
        data.put("data", null);
        return ApiResponse.success("借阅成功", data);
    }

}